<?php

class Profiles extends obj {

  var $data;
  var $profiles;

  public function __construct($file=NULL) {
    $found = load::exists($file, c::get('root.web'));
    if( !$found ) trigger_error("We can't find that board of directors data file", E_USER_ERROR);
    $this->load($found);
  }

    private function load($file) {
        $json = json_decode(f::read($file));
        if($json===NULL) $this->jsonHasError(json_last_error());
        $data = get_object_vars($json);
        $this->data = current($data);
        foreach($this->data as $k => $item) {
            $p = new Profile($item);
            if($p) $this->profiles[] = $p;
        }
    }

  public function get() {
    return $this->profiles;
  }

  public function getBySlug($slug) {
    foreach($this->profiles as $profile) {
      if($profile->getSlug() == $slug) {
        return $profile;
      }
    }
    return "Couldn't find that profile";
  }

  // TODO: Refactor into a JSON model
  private function jsonHasError($error) {
    switch ($error) {
        case JSON_ERROR_NONE:
            echo ' - No errors';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
        break;
        default:
            echo ' - Unknown error';
        break;
    }
    exit;
  }
}

class Profile extends obj {

  var $_;

  public function __construct($data=NULL) {
    if($data===NULL) return false;
    $this->_ = $data;
  }

  public function __call($name, $args) {
    $prefix = substr($name, 0, 3);
    $Noun   = substr($name, 3);
    $noun   = strtolower($Noun);

    // check for a 'has...' function call
    if($prefix === 'has') {
      if(isset($this->_->$noun)) return true;
      return false;
    }

    // check for a 'get...' function call
    if($prefix === 'get') {
      $func = "has$Noun";
      if($this->$func()) return $this->_->$noun;
      return NULL;
    }

    return NULL;
  }

  public function getSlug() { return slugify($this->_->name); }

  public function getAddress($plaintext=0) {
    $address = "";
    if($this->hasStreet()) $address .= $this-> getStreet();
    if(!$plaintext)        $address .= "<br>\n";
    if($plaintext)         $address .= ", ";
    if($this->hasCity())   $address .= $this-> getCity();
    if($this->hasState())  $address .= ", " . $this-> getState();
    if($this->hasZip())    $address .= " " . $this-> getZip();
    return $address;
  }
}